<!--
 * @Author: your name
 * @Date: 2022-03-09 16:52:21
 * @LastEditTime: 2022-04-27 01:49:33
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \react-antd-admin\vue-admin-template\src\views\carousel\index.vue
-->
<template>
  <div>
    <el-button type="primary"
               size='mini'
               style="margin: 5px 0 5px 2px"
               @click="toAdd">新增</el-button>
    <el-button type="primary"
               size='mini'
               style="margin: 5px 0 5px 2px"
               @click="toSee">预览</el-button>
    <el-table style="width: 100%"
              size='mini'
              v-loading='loading'
              :data='tableData'>
      <el-table-column width="80px"
                       type="index"
                       label="序号">
      </el-table-column>
      <el-table-column prop="name"
                       label="名称">
      </el-table-column>
      <el-table-column prop="introduce"
                       label="介绍">
      </el-table-column>
      <el-table-column align="center"
                       label="轮播图图片">
        <template slot-scope="scope">
          <el-popover placement="right"
                      width="225"
                      trigger="hover">
            <img :src="scope.row.url"
                 width="200"
                 height="160">
            <img slot="reference"
                 :src="scope.row.url"
                 width="40"
                 height="40">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="status"
                       label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status? 'success': 'danger'">{{scope.row.status? '启用' : '禁用'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       width="100">
        <template slot-scope="scope">
          <el-button type="text"
                     size="small"
                     @click="toEdit(scope.row)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button style="color:red"
                     type="text"
                     size="small"
                     @click="toDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-div">
      <el-pagination size="mini"
                     :current-page="params.page"
                     :page-sizes="[2,5,10,15,20]"
                     :page-size="params.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :total="total" />
    </div>
    <div>
      <el-dialog :title="title"
                 :visible.sync="visible">
        <el-form ref="ruleForm"
                 :model="form"
                 :rules="rules">
          <el-form-item prop="name"
                        label="轮播图名称"
                        :label-width="formLabelWidth">
            <el-input v-model="form.name"
                      autocomplete="off" />
          </el-form-item>
          <el-form-item prop="url"
                        label="轮播图图片"
                        :label-width="formLabelWidth">
            <el-upload class="avatar-uploader"
                       :action="uploadFileURL"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess">
              <img v-if="imageUrl"
                   :src="imageUrl"
                   class="avatar">
              <i v-else
                 class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item prop="introduce"
                        label="介绍"
                        :label-width="formLabelWidth">
            <el-input v-model="form.introduce"
                      autocomplete="off" />
          </el-form-item>
          <el-form-item v-if="title === '修改轮播图信息'"
                        prop="status"
                        label="状态"
                        :label-width="formLabelWidth">
            <el-switch v-model="form.status"
                       active-color="#13ce66"
                       inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer"
             class="dialog-footer">
          <el-button @click="visible=false">取 消</el-button>
          <el-button type="primary"
                     @click="toSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <el-dialog title="大屏预览"
               :visible.sync="visible1"
               width="80%">
      <span>
        <el-carousel :interval="5000"
                     arrow="always">
          <el-carousel-item v-for="item in tableData"
                            :key="item.id"
                            :data="tableData">
            <img :src="item.url"
                 width="100%"
                 height="300px">
          </el-carousel-item>
        </el-carousel>
      </span>
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="visible1 = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uploadFileURL } from '@/utils/config'
import { createCarousel, updateCarousel, deleteCarousel, getAllCarousels } from '@/api/carousel'
export default {
  data() {
    return {
      tableData: [],
      loading: false,
      params: {
        page: 1,
        pageSize: 10
      },
      total: 0,
      form: {},
      title: '',
      visible: false,
      visible1: false,
      formLabelWidth: '100px',
      rules: {
        name: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        url: [{
          required: true,
          message: '请输入url',
          trigger: 'blur'
        }],
      },
      imageUrl: '',
      uploadFileURL
    };
  },
  created() {
    this.getAllCarousels()
  },
  mounted() {

  },
  watch: {
    params: {
      handler() {
        this.getAllCarousels()
      },
      deep: true
    }
  },
  methods: {
    async getAllCarousels() {
      this.loading = true;
      const res = await getAllCarousels({ ...this.params });
      this.tableData = res.list;
      this.total = res.total
      this.loading = false;
    },
    /**
     * @description: 分页每页条数发生变化的回调
     * @param {*} val  当前条数值
     * @return {*}
     */
    handleSizeChange(val) {
      this.params.pageSize = val
      this.params.page = 1
    },
    /**
     * @description: 页码发生变化的回调
     * @param {*} val  当前条数值
     * @return {*}
     */
    handleCurrentChange(val) {
      this.params.page = val
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.form.url = res.data.file
    },
    async beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    toAdd() {
      this.form = {}
      this.title = '添加轮播图信息'
      this.visible = true
      this.imageUrl = ''
    },
    toEdit(row) {
      this.form = { ...row }
      this.title = '修改轮播图信息'
      this.visible = true
      this.imageUrl = row.url
    },
    toSee() {
      this.visible1 = true
    },
    toSave() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let res;
          if (this.title === '添加轮播图信息') {
            res = await createCarousel(this.form)
          }
          if (this.title === '修改轮播图信息') {
            res = await updateCarousel(this.form)
          }
          this.$notify.success({
            title: '成功',
            message: res.message
          })
          this.getAllCarousels()
          this.visible = false
        } else {
          return false
        }
      })
    },
    toDelete(id) {
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await deleteCarousel({ id })
        this.$message({ type: 'success', message: res.message })
        this.getAllCarousels()
      })
    }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
